package com.edgclub.edg.activity;


import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.http.async.AsyncHttpResponseHandler;
import com.edgclub.edg.http.async.RequestParams;
import com.edgclub.edg.huanxin.DemoHelper;
import com.edgclub.edg.huanxin.db.DemoDBManager;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.UserData;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.EaseCommonUtils;

import java.io.File;
import java.io.FileNotFoundException;

import cz.msebera.android.httpclient.Header;

public class RegisterSelectIconActivity extends GzBaseTooolBarActivity implements View.OnClickListener{

    private LinearLayout choose_boy , choose_girl ;
    private TextView boy_text , girl_text;
    private ImageView boy_icon , girl_icon , userIocn ;
    private EditText user_name;
    private GlideUtils glideUtils=new GlideUtils();
    private int sexType=1;
    private String userPath="";
    private UserPrefUtils userPrefUtils;
    private User user;
    private boolean isLoad;
    @Override
    public int getContentView() {
        return R.layout.activity_register2;
    }

    @Override
    public void setTitleBarView() {
        setCustomActionBar();
        title.setText("欢迎来到EDG俱乐部");
        right_layout.setVisibility(View.VISIBLE);
        right_text.setVisibility(View.VISIBLE);
        main_back.setVisibility(View.GONE);
        right_text.setText("完成");
        right_layout.setOnClickListener(this);
    }

    @Override
    public void initView() {
        choose_boy = (LinearLayout) findViewById(R.id.choose_boy);
        choose_girl = (LinearLayout) findViewById(R.id.choose_girl);
        boy_text = (TextView) findViewById(R.id.boy_text);
        girl_text = (TextView) findViewById(R.id.girl_text);
        boy_icon = (ImageView) findViewById(R.id.boy_icon);
        girl_icon = (ImageView) findViewById(R.id.girl_icon);
        userIocn = (ImageView) findViewById(R.id.userIocn);
        user_name= (EditText) findViewById(R.id.user_name);

        userIocn.setOnClickListener(this);
        choose_girl.setOnClickListener(this);
        choose_boy.setOnClickListener(this);

    }

    @Override
    public void initData() {
        userPrefUtils=new UserPrefUtils(this);
        user=userPrefUtils.getUser();
        if(null==user)user=new User();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.userIocn:
                Intent intent2 = new Intent(this, MultiImageSelectorActivity.class);
                intent2.putExtra("selectType",2);
                // 是否显示拍摄图片
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // 最大可选择图片数量
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                // 选择模式
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
//                startActivity(intent2);
                startActivityForResult(intent2, Constant.IMAGE_RESULT);
                break;
            case R.id.choose_boy:
                sexType=1;
                choose_boy.setBackground(getResources().getDrawable(R.drawable.register_selector1));
                choose_girl.setBackground(getResources().getDrawable(R.drawable.register_selector));
                boy_text.setTextColor(getResources().getColor(R.color.c10));
                girl_text.setTextColor(getResources().getColor(R.color.c4));
                boy_icon.setBackground(getResources().getDrawable(R.drawable.boy));
                girl_icon.setBackground(getResources().getDrawable(R.drawable.girl));
                if(null==userPath||"".equals(userPath)||"null".equals(userPath))
                userIocn.setImageResource(R.drawable.boypic);

                break;
            case R.id.choose_girl:
                sexType=0;
                choose_boy.setBackground(getResources().getDrawable(R.drawable.register_selector));
                choose_girl.setBackground(getResources().getDrawable(R.drawable.register_selector2));
                boy_text.setTextColor(getResources().getColor(R.color.c4));
                girl_text.setTextColor(getResources().getColor(R.color.c10));
                boy_icon.setBackground(getResources().getDrawable(R.drawable.boy2));
                girl_icon.setBackground(getResources().getDrawable(R.drawable.girl2));
                if(null==userPath||"".equals(userPath)||"null".equals(userPath))
                userIocn.setImageResource(R.drawable.girlpic);
                break;
            case R.id.right_layout:
//                if(!"".equals(userPath)&&!new File(userPath).exists()) {
                    updateUsetInfo();
//                }else{
//                    icon();
//                }


                break;
        }
    }

    private void updateUsetInfo(){
        if(isLoad)return;
//        if(null==userPath||"".equals(userPath)||"null".equals(userPath)){
//            StringUtils.postToast(this,"请上传自己的头像！");
//            return;
//        }
        if("".equals(user_name.getText()+"")){
            StringUtils.postToast(this,"请您留下大名！");
            return;
        }
        RequestParams userParam=new RequestParams();
        userParam.put("userId",user.getId());
        userParam.put("nick",user_name.getText()+"");
        userParam.put("sex",""+sexType);


        try {
            if(null!=userPath && !"".equals(userPath) && !"null".equals(userPath)) {
                userParam.put("logo", new File(userPath));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        new UserApi(this).getUpdateInfo(userParam, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                showDialog("正在提交数据，请稍后...",false);
                isLoad=true;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                dismissDialog();
                isLoad=false;
                try {
                    String recString= null;
                    recString = new String(responseBody);
                    if(JSONHelper.isSuccess(recString)){
                        UserData userData= JsonUtil.getMode(recString,UserData.class);
                        if(null!=userData&&null!=userData.getData()){
                            userPrefUtils.saveUser(userData.getData());
                        }
                        login();
                    }else{
                        StringUtils.postToast(RegisterSelectIconActivity.this,recString+"");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                dismissDialog();
                isLoad=false;
                Toast.makeText(RegisterSelectIconActivity.this,"网络异常，请稍后再试",Toast.LENGTH_SHORT).show();
            }
        });
    }

//    private void icon() {
//        UserParam param = new UserParam();
//        param.setUserId(user.getId());
//        param.setNick(user_name.getText() + "");
//        param.setSex(sexType+"");
//        new UserApi(this).getUpdateInfopost(param, this);
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Constant.IMAGE_RESULT) {
                 userPath=data.getStringExtra("userPath")+"";
                glideUtils.Glidde_loadCropCircleImage(RegisterSelectIconActivity.this,userPath,userIocn);
            }
        }
    }


    /**
     * 环信登录
     */
    public void login() {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }

        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        DemoDBManager.getInstance().closeDB();
        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(user.getNick());
        final long start = System.currentTimeMillis();
        // 调用sdk登陆方法登陆聊天服务器
        EMClient.getInstance().login(user.getImid(),userPrefUtils.getPSW(), new EMCallBack() {

            @Override
            public void onSuccess() {
                EMClient.getInstance().updateCurrentUserNick(user.getNick());
                dismissDialog();
                // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                // ** manually load all local groups and
                GuZhiApplication.isFirstMianActivity=true;
                Intent intent=new Intent(RegisterSelectIconActivity.this,GzMainActivity.class);
                startActivity(intent);
                finish();
                // 进入主页面
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(final int code, final String message) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        dismissDialog();
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


//    @Override
//    public void onStart(String tag) {
//        showDialog("正在提交数据，请稍后...",false);
//        isLoad=true;
//    }
//
//    @Override
//    public void onSuccess(String response, String tag) {
//        dismissDialog();
//        isLoad=false;
//
//            if(JSONHelper.isSuccess(response)){
//                UserData userData= JsonUtil.getMode(response,UserData.class);
//                if(null!=userData&&null!=userData.getData()){
//                    userPrefUtils.saveUser(userData.getData());
//                }
//                login();
//            }else{
//                showToast(JSONHelper.getResultMsg(response));
//        }
//    }
//
//    @Override
//    public void onFaile(VolleyError volleyError, String tag) {
//        dismissDialog();
//        isLoad=false;
//        ResultCode.toastVolleyError(this,volleyError);
//    }
}
